package com.smart.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.entity.*;
import com.smart.mapper.ArticleLabelMapper;
import com.smart.mapper.ArticleMapper;
import com.smart.mapper.LabelMapper;
import com.smart.service.ArticleService;
import com.smart.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    LabelMapper labelMapper;

    @Autowired
    ArticleLabelMapper articleLabelMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Integer ArticleWrite(Map<String, String> temp) {

//        处理标签
        String str = temp.get("label");
        String[] split = str.split(";");
        List<String> imei = Arrays.asList(split);
//        通过set去重
        Set snSet = new HashSet<>(imei);
        split = (String[]) snSet.toArray(new String[0]);
//        查询数据库是否已有
        List<Label> judge = labelMapper.judge(split);
//        如果有就把数组相同的删掉
        List<String> tempList = Arrays.asList(split);
        //Arrays.asList(filters) 迭代器实现类 不支持remove() 删除，多一步转化
        List<String> arrList = new ArrayList<String>(tempList);

//        定义一个存id列表
        List<Integer> labelId = new ArrayList<Integer>();
//        判断
        for (int j = 0; j < arrList.size(); j++) {
            for (int i = 0; i < judge.size(); i++) {
                if (arrList.get(j).equals(judge.get(i).getLabelName())) {
                    labelId.add(judge.get(i).getLabelId());
                    arrList.remove(j);
                    if (arrList.size() == 0) break;
                    if (j == 0) j = 0;
                    else j = j - 1;
                }
            }
        }
//        将不存在的插入数据库
//        待优化---未来实现批量存储
        if (arrList.size()>0){
            for (int i=0;i<arrList.size();i++){
                Label label = new Label();
                label.setLabelName(arrList.get(i));
                labelMapper.insert(label);
                Integer id = label.getLabelId();
                labelId.add(id);
            }
        }


        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUsers().getUid();
        Article article = JSON.parseObject(JSON.toJSONString(temp), Article.class);
        article.setArticleState(1);
        article.setArticleDate(new Date());
        article.setArticleAuthor(userId);
        System.out.println(article);
        articleMapper.insert(article);
//      插入文章拿到对应id
        Integer id = article.getId();
        //        待优化---未来实现批量存储
        if (labelId.size()>0){
            for (int i=0;i<labelId.size();i++){
                Article_Label articleLabel = new Article_Label();
                articleLabel.setArticle_id(id);
                articleLabel.setLabel_id(labelId.get(i));
                articleLabelMapper.insert(articleLabel);
            }
        }

        return 0;
    }

    @Override
    public Integer ArticleDelete(Integer id) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("id",id);
        articleMapper.delete(articleQueryWrapper);
        QueryWrapper<Article_Label> articleLabelQueryWrapper = new QueryWrapper<>();
        articleLabelQueryWrapper.eq("article_id", id);
        articleLabelMapper.delete(articleLabelQueryWrapper);
        return null;
    }


    @Override
        public Map<String, Object> ArticleAll (Integer currentPage, Integer pageSize){
            Page<Article> page = new Page<>(currentPage, pageSize);//查询的N页，显示N条数据
            IPage<Article> iPage = articleMapper.selectPage(page, null);
            Map<String, Object> map = new HashMap<>();
            map.put("total", iPage.getTotal());
            map.put("current", iPage.getCurrent());
            map.put("data", iPage.getRecords());
            return map;
        }

        @Override
        public Map<String, Object> ArticleList (Integer currentPage, Integer pageSize){
            Page<Article_List> page = new Page<>(currentPage, pageSize);//查询的N页，显示N条数据
            IPage<Article_List> iPage = articleMapper.articlelist(page);
            Map<String, Object> map = new HashMap<>();
            map.put("total", iPage.getTotal());
            map.put("current", iPage.getCurrent());
            map.put("data", iPage.getRecords());
            return map;
        }

    @Override
    public Map<String, Object> ArticleDetails(Integer id) {
        List<ArticleDetails> articles = articleMapper.articleDetails(id);
        List<String> temp = new ArrayList<String>();
        for(int i = 0; i < articles.size(); i++){
            temp.add(articles.get(i).getLabelName());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id",articles.get(0).getId());
        map.put("realname",articles.get(0).getRealname());
        map.put("article_date",articles.get(0).getArticleDate());
        map.put("article_content",articles.get(0).getArticleContent());
        map.put("article_title",articles.get(0).getArticleTitle());
        map.put("article_state",articles.get(0).getArticleState());
        map.put("class_name",articles.get(0).getClassName());
        map.put("label_name",temp);
        return map;
    }

    @Override
    public Map<String, Object> ArticleIndexList(Integer currentPage, Integer pageSize) {
        Page<Article_List> page = new Page<>(currentPage, pageSize);//查询的N页，显示N条数据
        IPage<ArticleDetails> iPage = articleMapper.articleIndexList(page);

        for(int i=0;i<iPage.getRecords().size();i++){
            int id = iPage.getRecords().get(i).getId();
            System.out.println(iPage.getRecords().get(i).getId());
            String temp = "";
            List<ArticleDetails> articles = articleMapper.articleDetails(id);
            for(int j = 0; j < articles.size(); j++){
                temp += (articles.get(j).getLabelName()+";");
            };
            iPage.getRecords().get(i).setLabelName(temp);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", iPage.getTotal());
        map.put("current", iPage.getCurrent());
        map.put("data", iPage.getRecords());
        return map;
    }

    @Override
    public Map<String, Object> ArticleListClass(Integer currentPage, Integer pageSize,Integer classId) {
        Page<Article_List> page = new Page<>(currentPage, pageSize);//查询的N页，显示N条数据
        IPage<ArticleDetails> iPage = articleMapper.articleListClass(page,classId);

        for(int i=0;i<iPage.getRecords().size();i++){
            int id = iPage.getRecords().get(i).getId();
            System.out.println(iPage.getRecords().get(i).getId());
            String temp = "";
            List<ArticleDetails> articles = articleMapper.articleDetails(id);
            for(int j = 0; j < articles.size(); j++){
                temp += (articles.get(j).getLabelName()+";");
            };
            iPage.getRecords().get(i).setLabelName(temp);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", iPage.getTotal());
        map.put("current", iPage.getCurrent());
        map.put("data", iPage.getRecords());
        return map;
    }
}